<template>
    <div>
        <n-grid :x-gap="24">
            <n-grid-item span="12">
              <n-card>
                <n-space justify="center">
                  <n-el v-if="selectedPic != '' && selectedPic != null  " style="background: var(--hover-color);margin-top:10px">
                    <n-space    style="padding: 10px;">
                      <n-image
                          :width="500"
                          :src=fileFunction.getViewFilePathByUserFileId(selectedPic)
                      />
                    </n-space>
                  </n-el>
                </n-space>
                <n-space style="margin-top:20px" >
                  <n-scrollbar  x-scrollable style="max-height: 80px">
                    <div style="white-space: nowrap;" >
                      <n-image v-for="pic in picList"
                               preview-disabled
                               :lazy="true"
                               :width="70"
                               size="small"
                               @click="selectedPic = pic"
                               :class="{ 'selected': pic == selectedPic }"
                               style="margin-left: 10px;"
                               :src=fileFunction.getViewFilePathByUserFileId(pic)
                      />
                    </div>
                  </n-scrollbar>
                </n-space>
              <n-form :label-width="100" label-placement="left" :model="text2ImgPrompt" :rules="rules" ref="formRef">
                <n-divider title-placement="left">
                  提示词
                </n-divider>
                <n-form-item path="prompt">
                  <n-input v-model:value="text2ImgPrompt.prompt"  type="textarea" style="height: 100px"/>
                  <n-button  type="primary" @click="generateImg" :loading="buttonLoading" style="height: 100px;margin-left:5px;">
                    生成
                  </n-button>
                </n-form-item>
                <div>
                    <n-space aria-placeholder="right">
                        <n-button ghost>
                            重置
                        </n-button>
                        <n-button type="primary" @click="generateImg" :loading="buttonLoading" >
                            生成
                        </n-button>
                    </n-space>
                </div>
              </n-form>
              </n-card>
            </n-grid-item>
            <n-grid-item span="12">
              <n-card>
              <n-form :rules="rules" ref="formRef">
                <n-form-item label="Performance" path="performance">
                  <n-radio-group v-model:value="text2ImgPrompt.performance"  name="performance">
                    <n-space>
                      <n-radio value="Speed">
                        Speed
                      </n-radio>
                      <n-radio value="Quality">
                        Quality
                      </n-radio>
                    </n-space>
                  </n-radio-group>
                </n-form-item>

                <n-grid :cols="24" :x-gap="24">
                  <n-form-item-gi :span="6" label="Raw Mode" path="Raw Mode">
                    <n-checkbox v-model:checked="text2ImgPrompt.isRawMode">
                      Raw Mode
                    </n-checkbox>
                  </n-form-item-gi>
                  <n-form-item-gi :span="18" label="风格预设" path="styleId">
                    <n-select :options="styleOptions" v-model:value="text2ImgPrompt.imageStyle">
                    </n-select>
                  </n-form-item-gi>
                </n-grid>

                <n-grid :cols="24" :x-gap="24">
                  <n-form-item-gi :span="12" label="生成数量" path="imageNumber">
                    <n-input-number v-model:value="text2ImgPrompt.imageNumber" :max="4" :min="1">
                    </n-input-number>
                  </n-form-item-gi>
                  <n-form-item-gi :span="12" label="Sampling Sharpness" path="Sampling Sharpness">
                    <n-input-number v-model:value="text2ImgPrompt.samplingSharpness" :min="0" :max="30">
                    </n-input-number>
                  </n-form-item-gi>
                </n-grid>

                <n-form-item label="Seed" path="seed">
                  <n-space align="center">
                    <n-switch size="large" v-model:value="text2ImgPrompt.seed">
                      <template #checked>
                        随机
                      </template>
                      <template #unchecked>
                        自定义
                      </template>
                    </n-switch>
                    <n-input-number  v-model:value="text2ImgPrompt.seed" :min=0 />
                  </n-space>
                </n-form-item>

                <n-form-item label="反向提示词" path="negativePrompt">
                  <n-input v-model:value="text2ImgPrompt.negativePrompt">
                  </n-input>
                </n-form-item>

                <n-form-item label="图片尺寸" path="performance">
                  <n-radio-group v-model:value="text2ImgPrompt.aspectRatio"  name="performance">
                    <n-space>
                      <n-radio value="704×1408">
                        704×1408
                      </n-radio>
                      <n-radio value="704×1344">
                        704×1344
                      </n-radio>
                      <n-radio value="768×1344">
                        768×1344
                      </n-radio>
                      <n-radio value="768×1280">
                        768×1280
                      </n-radio>
                      <n-radio value="832×1216">
                        832×1216
                      </n-radio>
                      <n-radio value="832×1152">
                        832×1152
                      </n-radio>
                      <n-radio value="896×1152">
                        896×1152
                      </n-radio>
                      <n-radio value="896×1088">
                        896×1088
                      </n-radio>
                      <n-radio value="960×1088">
                        960×1088
                      </n-radio>
                      <n-radio value="960×1024">
                        960×1024
                      </n-radio>
                      <n-radio value="1024*1024">
                        1024*1024
                      </n-radio>
                      <n-radio value="1024×960">
                        1024×960
                      </n-radio>
                      <n-radio value="1088×960">
                        1088×960
                      </n-radio>
                      <n-radio value="1088×896">
                        1088×896
                      </n-radio>
                      <n-radio value="1152×896">
                        1152×896
                      </n-radio>
                      <n-radio value="1152×832">
                        1152×832
                      </n-radio>
                      <n-radio value="1216×832">
                        1216×832
                      </n-radio>
                      <n-radio value="1280×768">
                        1280×768
                      </n-radio>
                      <n-radio value="1344×768">
                        1344×768
                      </n-radio>
                      <n-radio value="1344×704">
                        1344×704
                      </n-radio>
                      <n-radio value="1408×704">
                        1408×704
                      </n-radio>
                      <n-radio value="1472×704">
                        1472×704
                      </n-radio>
                      <n-radio value="1536×640">
                        1536×640
                      </n-radio>
                      <n-radio value="1600×640">
                        1600×640
                      </n-radio>
                      <n-radio value="1664×576">
                        1664×576
                      </n-radio>
                      <n-radio value="1728×576">
                        1728×576
                      </n-radio>
                    </n-space>
                  </n-radio-group>
                </n-form-item>
              </n-form>
              </n-card>
            </n-grid-item>
      </n-grid>
    </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue';
import {useMessage} from 'naive-ui';
// @ts-ignore
import fileFunction from '@/libs/globalFunction/file.js'
import {promptControllerApi} from "@/api/prompt/prompt.api";
import {fooocusControllerApi} from "@/api/paint/fooocusController.api";
const checked = ref(false)
const formRef: any = ref(null);
const styleOptions = ref([])
const message = useMessage();
const imageSrc = ref(); // 默认图片的URL

// 初始化数据
const text2ImgPrompt:Fooocus.Txt2ImgModel  =  reactive({
    prompt: '',
    imageStyle: 'Fooocus V2',
    isRawMode: false,
    performance:'Speed',
    aspectRatio: '1152×896',
    imageNumber: 1,
    seed:0,
    samplingSharpness: 2,
    random: true,
    negativePrompt:'',
    baseModelName: 'sd_xl_base_1.0_0.9vae.safetensors',
    refinerModelName:'sd_xl_refiner_1.0_0.9vae.safetensors',
    firstLoraModelName:'sd_xl_offset_example-lora_1.0.safetensors',
    firstLoraWeight: 0.5,
    secondLoraModelName: 'None',
    secondLoraWeight: -2,
    thirdLoraModelName: 'None',
    thirdLoraWeight: -2,
    fourthLoraModelName: 'None',
    fourthLoraWeight: -2,
    fifthLoraModelName: 'None',
    fifthLoraWeight: -2
});
const drawerWidth = ref(0)
const picList = ref([])
const selectedPic = ref(null)
const buttonLoading = ref(false)

const rules = {
  prompt: {
    required: true,
    message: '请输入提示词',
    trigger: 'submit',
  }
};

/**初始化事件**/
onMounted(() => {
  // 设置当前drawerWidth 宽度
  drawerWidth.value = window.innerWidth - 300;
  window.addEventListener('resize', handleResize);
  getStyleOptions()
})

// 窗口宽度变化
const handleResize = () => {
  drawerWidth.value = window.innerWidth - 300;
}

const getStyleOptions = () =>{
  promptControllerApi.getPaintStyleOption('stable-diffusion-xl').then(res=>{
    if(res.code === 200){
      res.data.forEach((item:any)=>{
        // @ts-ignore
        styleOptions.value.push({
          label: item.templateName,
          value: item.templateCode,
          prompt: item.templatePrompt,
          negativePrompt: item.templateNegativePrompt,
        })
      })
    } else {
      message.error(res.msg);
    }
  })
}




/**提交任务**/
const generateImg =  async () => {
  buttonLoading.value = true;
  try {
    // 更新prompt
    const res = await fooocusControllerApi.submitTxtToImage(text2ImgPrompt)
    console.log(res)
    if (res.code === 200) {
      const data = res.data;
      if (data.code === 1) {
        checkTask(data.result);
      }
    } else {
      message.error(res.message);
    }
  }catch (e){
    buttonLoading.value = false
  }
}



let timeoutId = ref();// 保存当前的 setTimeout 的 id
const checkTask = async (taskId:string) => {
  const {data} = await fooocusControllerApi.checkTask(taskId)
  if(data.taskStatus == 'SUCCESS') {
    const images = data.imageUrl.split(',')
    selectedPic.value = images[0]
    for(let i = 0; i < images.length; i++){
      picList.value.push(images[i])
    }
    buttonLoading.value = false
  }else if(data.taskStatus == 'FAILURE'){
    clearTimeout(timeoutId.value);
  }else {
    timeoutId.value = setTimeout(() => {
      checkTask(taskId);
    }, 2000); // 每隔0.5秒调用一次 checkTask
  }
}


const loadConfig = (storyCreatorConfig:Creator.StoryCreatorConfig,selectedResource:string) =>{
  if(selectedResource == storyCreatorConfig.resourceId) {
    const config = JSON.parse(storyCreatorConfig.paintConfigText)
    text2ImgPrompt.prompt = config.prompt
    text2ImgPrompt.imageStyle = config.imageStyle
    text2ImgPrompt.isRawMode = config.isRawMode
    text2ImgPrompt.performance = config.performance
    text2ImgPrompt.aspectRatio = config.aspectRatio
    text2ImgPrompt.imageNumber = config.imageNumber
    text2ImgPrompt.seed = config.seed
    text2ImgPrompt.samplingSharpness = config.samplingSharpness
    text2ImgPrompt.negativePrompt = config.negativePrompt
    text2ImgPrompt.baseModelName = config.baseModelName
    text2ImgPrompt.refinerModelName = config.refinerModelName
    text2ImgPrompt.firstLoraModelName = config.firstLoraModelName
    text2ImgPrompt.firstLoraWeight = config.firstLoraWeight
    text2ImgPrompt.secondLoraModelName = config.secondLoraModelName
    text2ImgPrompt.secondLoraWeight = config.secondLoraWeight
    text2ImgPrompt.thirdLoraModelName = config.thirdLoraModelName
    text2ImgPrompt.thirdLoraWeight = config.thirdLoraWeight
    text2ImgPrompt.fourthLoraModelName = config.fourthLoraModelName
    text2ImgPrompt.fourthLoraWeight = config.fourthLoraWeight
    text2ImgPrompt.fifthLoraModelName = config.fifthLoraModelName
    text2ImgPrompt.fifthLoraWeight = config.fifthLoraWeight
  }
}

const getConfig = () =>{
  return text2ImgPrompt
}

defineExpose({
  getConfig,loadConfig
})

</script>
<style>
.selected {
  border: 3px solid #8250df;
}
</style>
